<template>
  <div class="contract-management">
    <!-- 筛选栏 -->
    <div class="filter-container mb-4">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="filter.tenantName" placeholder="租户姓名" @keyup.enter="refreshList"></el-input>
        </el-col>
        <el-col :span="6">
          <el-input v-model="filter.contractId" placeholder="合同编号" @keyup.enter="refreshList"></el-input>
        </el-col>
        <el-col :span="6">
          <el-date-picker
              v-model="filter.startDate"
              type="date"
              placeholder="起始日期"
              @change="refreshList"
          ></el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-date-picker
              v-model="filter.endDate"
              type="date"
              placeholder="到期日期"
              @change="refreshList"
          ></el-date-picker>
        </el-col>
        <el-col :span="4" :offset="20">
          <el-button type="primary" @click="refreshList">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 合同列表 -->
    <el-table :data="displayContracts" style="width: 100%" stripe>
      <el-table-column prop="contractId" label="合同编号" width="150" />
      <el-table-column label="租户信息" width="200">
        <template #default="scope">
          <div class="tenant-info">
            <span>{{ scope.row.tenantName }}</span>
            <span class="tenant-phone">{{ scope.row.tenantPhone }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="propertyAddress" label="房源地址" width="200" />
      <el-table-column prop="startDate" label="起始日期" width="120" />
      <el-table-column prop="endDate" label="到期日期" width="120" />
      <el-table-column prop="rent" label="月租金(元)" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="openRenewDialog(scope.row)"
              :disabled="scope.row.status !== 'active'"
          >
            续约管理
          </el-button>
          <el-button
              type="info"
              size="small"
              @click="viewContract(scope.row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="mt-4"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredContracts.length"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 续约弹窗 -->
    <el-dialog v-model="dialogVisible" title="合同续约" width="40%">
      <el-form :model="renewForm" :rules="rules" ref="renewFormRef" label-width="120px">
        <el-form-item label="合同编号" prop="contractId">
          <el-input v-model="renewForm.contractId" disabled></el-input>
        </el-form-item>
        <el-form-item label="租户姓名" prop="tenantName">
          <el-input v-model="renewForm.tenantName" disabled></el-input>
        </el-form-item>
        <el-form-item label="原到期日" prop="oldEndDate">
          <el-input v-model="renewForm.oldEndDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="新到期日" prop="newEndDate">
          <el-date-picker
              v-model="renewForm.newEndDate"
              type="date"
              placeholder="选择新到期日"
              :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="月租金(元)" prop="newRent">
          <el-input v-model.number="renewForm.newRent" type="number"></el-input>
        </el-form-item>
        <el-form-item label="续约备注" prop="remark">
          <el-input
              v-model="renewForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入续约说明"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRenewSubmit">确认续约</el-button>
      </template>
    </el-dialog>

    <!-- 合同详情弹窗 -->
    <el-dialog v-model="detailVisible" title="合同详情" width="60%">
      <el-card class="contract-detail-card">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form label-width="120px">
              <el-form-item label="合同编号">
                <el-input v-model="contractDetail.contractId" disabled></el-input>
              </el-form-item>
              <el-form-item label="租户姓名">
                <el-input v-model="contractDetail.tenantName" disabled></el-input>
              </el-form-item>
              <el-form-item label="租户电话">
                <el-input v-model="contractDetail.tenantPhone" disabled></el-input>
              </el-form-item>
              <el-form-item label="房源地址">
                <el-input v-model="contractDetail.propertyAddress" disabled></el-input>
              </el-form-item>
              <el-form-item label="房源类型">
                <el-input v-model="contractDetail.propertyType" disabled></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12">
            <el-form label-width="120px">
              <el-form-item label="起始日期">
                <el-input v-model="contractDetail.startDate" disabled></el-input>
              </el-form-item>
              <el-form-item label="到期日期">
                <el-input v-model="contractDetail.endDate" disabled></el-input>
              </el-form-item>
              <el-form-item label="月租金(元)">
                <el-input v-model="contractDetail.rent" disabled></el-input>
              </el-form-item>
              <el-form-item label="付款周期">
                <el-input v-model="contractDetail.paymentCycle" disabled></el-input>
              </el-form-item>
              <el-form-item label="合同状态">
                <el-tag :type="getStatusType(contractDetail.status)">{{ getStatusText(contractDetail.status) }}</el-tag>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-form-item label="合同备注">
          <el-input v-model="contractDetail.remark" type="textarea" :rows="4" disabled></el-input>
        </el-form-item>
      </el-card>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 静态数据
const allContracts = ref([
  {
    contractId: 'HT20250701001',
    tenantName: '张三',
    tenantPhone: '13800138001',
    propertyAddress: '北京市朝阳区建国路88号现代城5号楼1502',
    propertyType: '公寓',
    startDate: '2025-01-01',
    endDate: '2025-12-31',
    rent: 3500,
    status: 'active',
    paymentCycle: '季度付',
    remark: '首次签约，租金押一付三'
  },
  {
    contractId: 'HT20250701002',
    tenantName: '李四',
    tenantPhone: '13900139002',
    propertyAddress: '北京市海淀区中关村大街1号海龙大厦12层',
    propertyType: '写字楼',
    startDate: '2025-03-15',
    endDate: '2025-09-14',
    rent: 8500,
    status: 'expiring',
    paymentCycle: '半年付',
    remark: '企业办公使用，含物业费'
  },
  {
    contractId: 'HT20250701003',
    tenantName: '王五',
    tenantPhone: '13700137003',
    propertyAddress: '上海市浦东新区张江高科技园区博云路2号浦软大厦12层',
    propertyType: '公寓',
    startDate: '2024-11-01',
    endDate: '2025-10-31',
    rent: 6800,
    status: 'active',
    paymentCycle: '月付',
    remark: '个人居住，环境安静'
  },
  {
    contractId: 'HT20250701004',
    tenantName: '赵六',
    tenantPhone: '13600136004',
    propertyAddress: '广州市天河区珠江新城冼村路5号保利威座1903',
    propertyType: '住宅',
    startDate: '2024-08-20',
    endDate: '2025-02-19',
    rent: 12000,
    status: 'expired',
    paymentCycle: '年付',
    remark: '家庭居住，已续约一次'
  },
  {
    contractId: 'HT20250701005',
    tenantName: '钱七',
    tenantPhone: '13500135005',
    propertyAddress: '深圳市南山区科技园南区科苑路15号科兴科学园B3栋801',
    propertyType: '商铺',
    startDate: '2025-03-10',
    endDate: '2025-09-09',
    rent: 18000,
    status: 'active',
    paymentCycle: '季度付',
    remark: '商业经营，人流量大'
  },
  {
    contractId: 'HT20250701006',
    tenantName: '孙八',
    tenantPhone: '13400134006',
    propertyAddress: '杭州市西湖区文三路90号东部软件园1号楼305',
    propertyType: '办公室',
    startDate: '2025-05-01',
    endDate: '2025-07-31',
    rent: 10500,
    status: 'expiring',
    paymentCycle: '半年付',
    remark: '创业团队使用，配套齐全'
  },
  {
    contractId: 'HT20250701007',
    tenantName: '周九',
    tenantPhone: '13300133007',
    propertyAddress: '成都市武侯区武侯祠大街231号1栋2单元601',
    propertyType: '住宅',
    startDate: '2024-12-10',
    endDate: '2025-12-09',
    rent: 4200,
    status: 'active',
    paymentCycle: '月付',
    remark: '两室一厅，拎包入住'
  },
  {
    contractId: 'HT20250701008',
    tenantName: '吴十',
    tenantPhone: '13200132008',
    propertyAddress: '南京市鼓楼区中山北路2号紫峰大厦38层',
    propertyType: '写字楼',
    startDate: '2025-02-15',
    endDate: '2025-08-14',
    rent: 9600,
    status: 'expiring',
    paymentCycle: '季度付',
    remark: '金融公司办公，视野开阔'
  },
  {
    contractId: 'HT20250701009',
    tenantName: '黄牛',
    tenantPhone: '13200132009',
    propertyAddress: '四川省眉山市彭山区四川大学锦江学院',
    propertyType: '写字楼',
    startDate: '2025-02-15',
    endDate: '2025-08-14',
    rent: 9600,
    status: 'expiring',
    paymentCycle: '年度付',
    remark: '学校，视野开阔'
  },
  {
    contractId: 'HT20250701009',
    tenantName: '覃宏',
    tenantPhone: '13200132009',
    propertyAddress: '四川省眉山市金科小区',
    propertyType: '写字楼',
    startDate: '2025-02-15',
    endDate: '2025-08-14',
    rent: 9600,
    status: 'expiring',
    paymentCycle:'年度付 ',
    remark: '学校，视野开阔'
  }
]);

// 核心数据
const filter = ref({
  tenantName: '',
  contractId: '',
  startDate: '',
  endDate: ''
});

const currentPage = ref(1);
const pageSize = ref(5);

// 计算属性：筛选后的合同
const filteredContracts = computed(() => {
  return allContracts.value.filter(item => {
    if (filter.value.tenantName && !item.tenantName.includes(filter.value.tenantName)) {
      return false;
    }
    if (filter.value.contractId && !item.contractId.includes(filter.value.contractId)) {
      return false;
    }
    if (filter.value.startDate && dayjs(item.startDate).isBefore(filter.value.startDate)) {
      return false;
    }
    if (filter.value.endDate && dayjs(item.endDate).isAfter(filter.value.endDate)) {
      return false;
    }
    return true;
  });
});

// 计算属性：当前页显示的合同
const displayContracts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredContracts.value.slice(start, end);
});

// 弹窗相关
const dialogVisible = ref(false);
const detailVisible = ref(false);
const currentContract = ref(null);
const renewFormRef = ref(null);
const contractDetail = ref({});

const renewForm = reactive({
  contractId: '',
  tenantName: '',
  oldEndDate: '',
  newEndDate: '',
  newRent: 0,
  remark: ''
});

const rules = {
  newEndDate: [
    { required: true, message: '请选择新的到期日期', trigger: 'change' }
  ],
  newRent: [
    { required: true, message: '请输入新的租金金额', trigger: 'blur' },
    { type: 'number', message: '租金必须为数字', trigger: 'blur' },
    { min: 0, message: '租金不能为负数', trigger: 'blur' }
  ]
};

// 初始化加载
onMounted(() => {
  // 自动计算合同状态
  updateContractStatus();
});

// 更新合同状态（根据当前日期计算）
const updateContractStatus = () => {
  const today = dayjs();

  allContracts.value.forEach(contract => {
    const endDate = dayjs(contract.endDate);
    const diffDays = endDate.diff(today, 'day');

    if (diffDays < 0) {
      contract.status = 'expired';
    } else if (diffDays <= 30) {
      contract.status = 'expiring';
    } else {
      contract.status = 'active';
    }
  });
};

// 状态文本转换
const getStatusText = (status) => {
  const statusMap = {
    'active': '有效',
    'expiring': '即将到期',
    'expired': '已过期',
    'renewed': '已续约'
  };
  return statusMap[status] || status;
};

// 状态标签类型转换
const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',
    'expiring': 'warning',
    'expired': 'danger',
    'renewed': 'info'
  };
  return typeMap[status] || 'default';
};

// 打开续约弹窗
const openRenewDialog = (contract) => {
  currentContract.value = contract;
  renewForm.contractId = contract.contractId;
  renewForm.tenantName = contract.tenantName;
  renewForm.oldEndDate = contract.endDate;
  // 默认续约一年
  renewForm.newEndDate = dayjs(contract.endDate).add(1, 'year').format('YYYY-MM-DD');
  renewForm.newRent = contract.rent;
  renewForm.remark = '';
  dialogVisible.value = true;
};

// 查看合同详情
const viewContract = (contract) => {
  contractDetail.value = { ...contract };
  detailVisible.value = true;
};

// 禁用过去日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000; // 不能选择今天之前的日期
};

// 提交续约
const handleRenewSubmit = async () => {
  try {
    await renewFormRef.value.validate();

    // 确认对话框
    await ElMessageBox.confirm(
        `确定要为 ${renewForm.tenantName} 的合同（${renewForm.contractId}）续约至 ${renewForm.newEndDate} 吗？`,
        '确认续约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 更新本地数据
    const contractIndex = allContracts.value.findIndex(
        item => item.contractId === renewForm.contractId
    );

    if (contractIndex !== -1) {
      allContracts.value[contractIndex].endDate = renewForm.newEndDate;
      allContracts.value[contractIndex].rent = renewForm.newRent;
      allContracts.value[contractIndex].status = 'renewed';

      // 添加续约备注
      if (renewForm.remark) {
        allContracts.value[contractIndex].remark += `\n续约备注: ${renewForm.remark}`;
      }

      ElMessage.success('续约成功！');
      dialogVisible.value = false;
    }
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message);
    } else {
      // 用户取消操作
      ElMessage.info('已取消续约操作');
    }
  }
};

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 重置筛选
const resetFilter = () => {
  filter.value = {
    tenantName: '',
    contractId: '',
    startDate: '',
    endDate: ''
  };
};

// 刷新列表
const refreshList = () => {
  // 更新状态并刷新列表
  updateContractStatus();
};
</script>

<style scoped>
.contract-management {
  padding: 20px;
}

.filter-container {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.tenant-info {
  display: flex;
  flex-direction: column;
}

.tenant-phone {
  color: #8c8c8c;
  font-size: 12px;
}

.contract-detail-card {
  margin: 15px;
}
</style>